package com.kaigejava.message;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * Created by kaigejava on 2019/7/10.
 * 带有附加信息的消息生产者
 */
public class Procuder {

    public static void main(String[] args) throws IOException, TimeoutException {
        //1:创建一个connectioFactory工厂对象，并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
            //设置ip 端口 vhost等
        connectionFactory.setHost("192.168.31.130");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2：通过工厂对象获取到connection对象
        Connection connection = connectionFactory.newConnection();

        //3：通过connection对象获取到一个消息通信的通道 channel
        Channel channel = connection.createChannel();

        /**
         * 设置附加信息的消息
         */
        Map<String,Object>  headerMap = new HashMap<>();
        headerMap.put("msg","这里是自定义的消息体");
        AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
                .appId("1") //设置appid
                .deliveryMode(2)    //持久化
                //.expiration("10000")    //过期时间10s
                .contentEncoding("UTF-8")   //设置编码格式
                .headers(headerMap)     //自定义的属性
                .build();
        // 4：通过channel发送数据
        /**
         * 参数说明：
         * exchange: 数据路由 routingKey: props: 消息描述body:消息体。字节数组
         */

        for(int i = 0;i<5;i++){
            String mst = "hi Rabbit mq!"+i;
            //将 自定义属性传递
           // channel.basicPublish("","mytest001",null,mst.getBytes());
            channel.basicPublish("","mytest001",properties,mst.getBytes());
        }
        System.out.println("===>>>生产者发送消息完成。。。");
         //5：关闭流
        channel.close();
        connection.close();

    }
}
